package com.meida.paotui.app.handler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.egzosn.pay.common.api.PayService;
import com.egzosn.pay.common.bean.PayMessage;
import com.meida.common.base.handler.PayInfoHandler;
import com.meida.common.mybatis.entity.EntityMap;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaSave;
import com.meida.common.security.OpenHelper;
import com.meida.common.utils.FlymeUtils;
import com.meida.common.utils.OrderNoUtil;
import com.meida.module.pay.client.entity.PayInfo;
import com.meida.module.pay.provider.handler.PaySuccessHandler;
import com.meida.module.pay.provider.service.PayInfoService;
import com.meida.module.user.client.entity.AppUser;
import com.meida.module.user.provider.service.AppUserService;
import com.meida.paotui.bus.client.entity.BusCustomer;
import com.meida.paotui.bus.client.entity.BusCustomerdetail;
import com.meida.paotui.bus.client.entity.BusTrade;
import com.meida.paotui.bus.provider.mapper.BusTradeMapper;
import com.meida.paotui.bus.provider.service.BusCustomerService;
import com.meida.paotui.bus.provider.service.BusCustomerdetailService;
import com.meida.paotui.bus.provider.service.BusTradeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Map;
@Component("accountPayHandler")
public class AccountPayHandler implements PayInfoHandler, PaySuccessHandler {
    @Autowired
    private PayInfoService payInfoService;

    @Autowired
    private AppUserService userService;

    @Autowired
    private BusTradeService tradeService;
    @Autowired
    private BusCustomerService customerService;
    @Autowired
    private OrderNoUtil orderNoUtil;
    @Resource
    private BusTradeMapper busTradeMapper;
    @Autowired
    private BusTradeService busTradeService;
    @Autowired
    private BusCustomerdetailService  busCustomerdetailService;

    @Override
    public ResultBody validate(CriteriaSave cs, EntityMap requestMap) {
        Long companyId = OpenHelper.getCompanyId();
        Long userId = OpenHelper.getUserId();
        AppUser user = userService.getById(userId);
        String userType = user.getUserType();
        return ResultBody.ok();
    }

    @Override
    public void prepare(CriteriaSave cs, EntityMap params) {
    }

    @Override
    public void complete(CriteriaSave cs, EntityMap params, Object object) {

    }

    /**
     * 创建支付信息
     *
     * @param cs         对象模型
     * @param requestMap 参数接收
     * @param outTradeNo 订单号
     * @return
     */
    @Override
    public Object getPayInfo(CriteriaSave cs, EntityMap requestMap, String outTradeNo) {
        PayInfo payInfo = cs.getEntity(PayInfo.class);
        Long customerId = requestMap.getLong("tradeId");
        BusCustomer customer = customerService.getById(customerId);
        if(customer.getRechargeType().equals("2")){
            payInfo.setOutTradeNo(outTradeNo);
            payInfo.setOrderTitle("购买优惠券");
            payInfo.setBusId(customerId);
            payInfo.setOrderEntity(BusCustomer.class.getSimpleName());
            payInfo.setOrderBody(customer.getTicketTittle());
            payInfo.setOrderAmount(customer.getPayment());
        }else{
            payInfo.setOutTradeNo(outTradeNo);
            payInfo.setOrderTitle("账户充值");
            payInfo.setBusId(customerId);
            payInfo.setOrderEntity(BusCustomer.class.getSimpleName());
            payInfo.setOrderBody(customer.getTicketTittle());
            payInfo.setOrderAmount(customer.getPayment());

        }

        return payInfo;
    }

    /**
     * 订单回调检验
     *
     * @param payMessage 支付回调消息
     * @param context    上下文参数,可传递到success方法内
     * @param payService 支付服务
     * @param outTradeNo 订单号
     * @return
     */
    @Override
    public boolean validate(PayMessage payMessage, Map<String, Object> context, PayService payService, String outTradeNo) {
        return payInfoService.validate(outTradeNo);
    }


    /**
     * 订单回调业务处理
     *
     * @param payMessage 支付回调消息
     * @param outTradeNo 订单号
     * @param context    上下文参数
     * @param payService 支付服务
     * @return
     */
    @Override
    public boolean success(PayMessage payMessage, String outTradeNo, Map<String, Object> context, PayService payService) {
        System.out.print("========================================充值支付回调======================================");
        //获取创建订单时参数
        EntityMap params = payInfoService.getOrderParams(outTradeNo);
        PayInfo info =payInfoService.findByOutTradeNo(outTradeNo);
        if(FlymeUtils.isNotEmpty(info)){
            BusCustomer customer= customerService.getById(info.getBusId());
            EntityMap  map =new EntityMap();
            map.put("userId",info.getUserId());
            EntityMap use_map = busTradeMapper.findblance(map);
            if(customer.getRechargeType().equals("1")){
                BusTrade trade = new BusTrade();
                if(ObjectUtils.isNotEmpty(use_map)){
                    BigDecimal balance = use_map.getBigDecimal("balance");
                    trade.setBalance(balance.add(info.getOrderAmount()));
                }else{
                    trade.setBalance(info.getOrderAmount());
                }
                trade.setBusinessId(outTradeNo);
                trade.setTradeExplain("账户充值");
                trade.setTradeSum(info.getOrderAmount());
                trade.setTradeType(1);
                trade.setType(1);
                trade.setUserId(info.getUserId());
                trade.setStatus(1);
                boolean a = busTradeService.save(trade);
            }
            if(customer.getRechargeType().equals("2")){
                BusTrade trade = new BusTrade();
                if(ObjectUtils.isNotEmpty(use_map)){
                    if(ObjectUtils.isNotEmpty(use_map.getBigDecimal("balance"))){
                        trade.setBalance(use_map.getBigDecimal("balance"));
                    }
                }else{
                    trade.setBalance(BigDecimal.ZERO);
                }
                trade.setBusinessId(outTradeNo);
                trade.setTradeExplain("优惠券充值");
                trade.setTradeSum(info.getOrderAmount());
                trade.setTradeType(1);
                trade.setType(1);
                trade.setUserId(info.getUserId());
                trade.setStatus(1);
                boolean a = busTradeService.save(trade);
                BusCustomer customer1=customerService.getById(info.getBusId());
                QueryWrapper<BusCustomerdetail> qw_d=new QueryWrapper<>();
                qw_d.eq("userId",info.getUserId());
                qw_d.eq("customerId",info.getBusId());
                BusCustomerdetail customerdetail=busCustomerdetailService.getOne(qw_d);
                if(FlymeUtils.isNotEmpty(customerdetail)){
                    customerdetail.setCoupCount(customerdetail.getCoupCount()+customer1.getTicketCount());
                    busCustomerdetailService.saveOrUpdate(customerdetail);
                }else{
                    BusCustomerdetail customerdetail_new =new BusCustomerdetail();
                    customerdetail_new.setCoupCount(customer1.getTicketCount());
                    customerdetail_new.setCustomerId(customer1.getCustomerId());
                    customerdetail_new.setUserId(info.getUserId());
                    busCustomerdetailService.save(customerdetail_new);
                }
             }
        }
             return true;
    }
}
